<template>
  <div>
    <div style="height: 20px"></div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          label-width="70"
          label="旧密码"
          required
          placeholder="请输入旧密码"
          v-model="FormData.OldPassWord"
          autocomplete="off"
          type="password"
          :rules="[
            {
              validator: OldPassWord,
              message: '旧密码不正确'
            }
          ]"
        />
        <van-field
          label-width="70"
          label="新密码"
          required
          autocomplete="off"
          placeholder="大小写英文、数字、符号。不低于6位"
          v-model="FormData.NewPassWord"
          type="password"
          :rules="[
            {
              pattern,
              message: '大小写英文、数字、符号。不低于6位'
            }
          ]"
        />
        <van-field
          label-width="70"
          label="确认密码"
          required
          autocomplete="off"
          type="password"
          placeholder="请输入确认密码"
          v-model="FormData.PassWord"
          :rules="[
            {
              validator: repeatPassWord,
              message: '确认密码和新密码不一致'
            }
          ]"
        />
      </van-cell-group>
      <div style="margin: 30px 16px" class="flex">
        <div style="flex: 1">
          <van-button
            round
            block
            type="primary"
            plain
            @click="router.push('/Information')"
          >
            返回
          </van-button>
        </div>
        <div style="flex: 2; margin-left: 10px">
          <van-button
            round
            block
            type="primary"
            :disabled="disabled"
            native-type="submit"
          >
            提交
          </van-button>
        </div>
      </div>
    </van-form>
  </div>
</template>

<script setup name="PassWord">
import { EditUserPWD } from '@/api/system/user';
import { useRouter } from 'vue-router';
import useUserStore from '@/store/modules/user.js';
const { proxy } = getCurrentInstance();
const userInfo = computed(() => useUserStore().userInfo);
const router = useRouter();
const FormData = ref({});
const pattern = /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{6,}/;
const disabled = ref(false);
function OldPassWord(val) {
  return userInfo.value.PWD == val;
}
function repeatPassWord(val) {
  return val == FormData.value.NewPassWord;
}
async function onSubmit() {
  try {
    let query = {
      ID: userInfo.value.ID,
      PassWord: FormData.value.PassWord
    };
    await EditUserPWD(query);
    proxy.$modal.toast('修改成功');
    useUserStore().editStoreUser({
      ...userInfo.value,
      PWD: FormData.value.PassWord
    });
    disabled.value = true;
    setTimeout(() => {
      router.push('/Information');
      disabled.value = false;
    }, 1500);
  } catch (error) {
    console.log(error);
  }
}
</script>

<style lang="scss" scoped></style>
